package com.adam.example;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.HealthStatus;
import co.elastic.clients.elasticsearch._types.Level;
import co.elastic.clients.elasticsearch.cluster.ElasticsearchClusterClient;
import co.elastic.clients.elasticsearch.cluster.HealthRequest;
import co.elastic.clients.elasticsearch.cluster.HealthResponse;
import co.elastic.clients.elasticsearch.cluster.health.IndexHealthStats;

import java.io.IOException;
import java.util.Map;

public class ClusterAdminExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient elasticsearchClient = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();
        ElasticsearchClusterClient clusterClient = elasticsearchClient.cluster();

        HealthRequest healthRequest = HealthRequest.of(healthRequestBuilder -> healthRequestBuilder
                .level(Level.Indices)
        );
        HealthResponse healthResponse = clusterClient.health(healthRequest);
        String clusterName = healthResponse.clusterName();
        int numberOfNodes = healthResponse.numberOfNodes();
        int numberOfDataNodes = healthResponse.numberOfDataNodes();
        HealthStatus healthStatus = healthResponse.status();
        System.out.println("集群名称" + clusterName + "，健康状态" + healthStatus + "，数据节点数" + numberOfDataNodes + "，节点数" + numberOfNodes);
        Map<String, IndexHealthStats> indexHealthStatsMap = healthResponse.indices();
        for(Map.Entry<String, IndexHealthStats> entry: indexHealthStatsMap.entrySet()) {
            String indexName = entry.getKey();
            IndexHealthStats indexHealthStats = entry.getValue();
            int numberOfShards = indexHealthStats.numberOfShards();
            int numberOfReplicas = indexHealthStats.numberOfReplicas();
            HealthStatus indexHealthStatus = indexHealthStats.status();
            System.out.println("索引" + indexName + "，分片数" + numberOfShards + "，副本数" + numberOfReplicas + "，状态" + indexHealthStatus);
        }

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
